const requestHelper = require('../../utils/request');
const buildUrl = requestHelper.buildUrl || ((url) => url);

Page({
  data: {
    // 快递公司列表
    expressCompanies: ['顺丰速运', '圆通快递', '中通快递', '申通快递', '韵达快递', '京东物流', '邮政EMS', '其他'],
    expressCompany: '',

    // 快递类型列表
    expressTypes: ['文件', '小件物品', '电子产品', '衣物', '食品', '日用品', '其他'],
    expressType: '',

    // 包裹大小列表
    packageSizes: ['S (小件)', 'M (中件)', 'L (大件)', 'XL (超大件)'],
    packageSize: '',

    // 表单数据
    packageWeight: '',
    pickupCode: '',
    address: '',
    deliveryAddress: '',
    note: '',
    suggestedFee: 0,

    // 用户信息（动态获取）
    order_user_id: null,
    canShowPage: false,
    isLoading: true
  },

  // 跳转到登录页
  navigateToLogin: function () {
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },

  onLoad: function (options) {
    console.log('📦 订单页面加载');
    this.checkAuthAndLoad();
  },

  onShow: function () {
    // 页面显示时再次检查（用户可能从登录页返回）
    const userId = wx.getStorageSync('userId');
    if (userId && !this.data.canShowPage) {
      console.log('🔄 用户已登录，重新加载页面');
      this.checkAuthAndLoad();
    }
  },

  // 检查权限并加载数据
  checkAuthAndLoad: function () {
    const app = getApp();

    app.checkLogin().then(userId => {
      if (userId) {
        console.log('✅ 权限验证通过，用户ID:', userId);
        this.setData({
          order_user_id: userId,
          canShowPage: true,
          isLoading: false
        });
        console.log('🎯 订单页面准备就绪');
      } else {
        console.log('⛔ 等待用户登录...');
        this.setData({
          isLoading: false,
          canShowPage: false
        });
      }
    });
  },

  // 选择快递公司
  onExpressCompanyChange: function (e) {
    const index = e.detail.value;
    const company = this.data.expressCompanies[index];
    this.setData({
      expressCompany: company
    });
    this.calculateFee();
  },

  // 选择快递类型
  onExpressTypeChange: function (e) {
    const index = e.detail.value;
    const type = this.data.expressTypes[index];
    this.setData({
      expressType: type
    });
    this.calculateFee();
  },

  // 选择包裹大小
  onPackageSizeChange: function (e) {
    const index = e.detail.value;
    const size = this.data.packageSizes[index];
    this.setData({
      packageSize: size
    });
    this.calculateFee();
  },

  // 输入预估重量
  onPackageWeightInput: function (e) {
    this.setData({
      packageWeight: e.detail.value
    });
    this.calculateFee();
  },

  // 输入取件码
  onPickupCodeInput: function (e) {
    this.setData({
      pickupCode: e.detail.value
    });
  },

  // 输入取件地址
  onAddressInput: function (e) {
    this.setData({
      address: e.detail.value
    });
  },

  // 输入送达地址
  onDeliveryAddressInput: function (e) {
    this.setData({
      deliveryAddress: e.detail.value
    });
  },

  // 输入备注
  onNoteInput: function (e) {
    this.setData({
      note: e.detail.value
    });
  },

  // 计算费用
  calculateFee: function () {
    const { expressCompany, packageSize, packageWeight } = this.data;
    let fee = 3.00; // 基础费用

    // 根据快递公司调整
    if (expressCompany.includes('顺丰') || expressCompany.includes('京东')) {
      fee += 1.00;
    }

    // 根据包裹大小调整
    if (packageSize.includes('M')) {
      fee += 1.00;
    } else if (packageSize.includes('L')) {
      fee += 2.00;
    } else if (packageSize.includes('XL')) {
      fee += 3.00;
    }

    // 根据重量调整（每0.5kg加0.5元）
    const weight = parseFloat(packageWeight) || 0;
    if (weight > 0) {
      fee += Math.ceil(weight / 0.5) * 0.5;
    }

    this.setData({
      suggestedFee: parseFloat(fee.toFixed(2))
    });
  },

  // 提交订单到后端
  submitOrder: function () {
    // 再次检查登录状态
    if (!this.data.order_user_id) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });

      // 跳转到登录页
      const app = getApp();
      app.checkLogin();
      return;
    }

    const {
      expressCompany, expressType, packageSize, packageWeight,
      pickupCode, address, deliveryAddress, note, order_user_id, suggestedFee
    } = this.data;

    // 表单验证
    if (!expressCompany) {
      wx.showToast({
        title: '请选择快递公司',
        icon: 'none'
      });
      return;
    }

    if (!expressType) {
      wx.showToast({
        title: '请选择快递类型',
        icon: 'none'
      });
      return;
    }

    if (!packageSize) {
      wx.showToast({
        title: '请选择包裹大小',
        icon: 'none'
      });
      return;
    }

    if (!packageWeight) {
      wx.showToast({
        title: '请输入预估重量',
        icon: 'none'
      });
      return;
    }

    if (!pickupCode) {
      wx.showToast({
        title: '请输入取件码',
        icon: 'none'
      });
      return;
    }

    if (!address) {
      wx.showToast({
        title: '请输入取件地址',
        icon: 'none'
      });
      return;
    }

    if (!deliveryAddress) {
      wx.showToast({
        title: '请输入送达地址',
        icon: 'none'
      });
      return;
    }

    console.log('📤 提交订单，用户ID:', order_user_id);

    // 显示加载中
    wx.showLoading({
      title: '提交中...',
    });

    // 调用后端API创建订单
    wx.request({
      url: buildUrl('/api/orders'),
      method: 'POST',
      data: {
        order_user_id: order_user_id,
        express_company: expressCompany,
        express_type: expressType,
        package_size: packageSize,
        package_weight: parseFloat(packageWeight),
        pickup_code: pickupCode,
        pickup_location: address,
        delivery_address: deliveryAddress,
        note: note,
        suggested_fee: suggestedFee
      },
      success: (res) => {
        wx.hideLoading();

        if (res.data.success) {
          console.log('✅ 订单创建成功:', res.data);
          wx.showToast({
            title: '订单提交成功！',
            icon: 'success',
            duration: 2000
          });

          // 清空表单
          this.clearForm();

          // 返回首页
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          console.error('❌ 订单创建失败:', res.data);
          wx.showToast({
            title: res.data.message || '提交失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        wx.hideLoading();
        console.error('💥 请求失败:', error);
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 清空表单
  clearForm: function () {
    this.setData({
      expressCompany: '',
      expressType: '',
      packageSize: '',
      packageWeight: '',
      pickupCode: '',
      address: '',
      deliveryAddress: '',
      note: '',
      suggestedFee: 0
    });
  }
})